package com.lloseng.ocsf.simplechat.phase1.server;

// This file contains material supporting section 3.7 of the textbook:
import com.langage.commande.serveur.message.cor.AbstractAnalyseurClientMessage;
import com.langage.commande.serveur.message.cor.AnalyseurCreateSondage;
import com.langage.commande.serveur.message.cor.AnalyseurLogin;
import com.langage.commande.serveur.ui.cor.AnalyseurClose;
import com.langage.commande.serveur.ui.cor.AnalyseurGetPort;
import com.langage.commande.serveur.ui.cor.AnalyseurQuit;
import com.langage.commande.serveur.ui.cor.AnalyseurSetPort;
import com.langage.commande.serveur.ui.cor.AnalyseurStart;
import com.langage.commande.serveur.ui.cor.AnalyseurStop;
import com.langage.commande.serveur.ui.cor.ChainAnalyseurServer;
import com.lloseng.ocsf.common.ChatIF;
import com.lloseng.ocsf.server.AbstractServer;
import com.lloseng.ocsf.server.ConnectionToClient;
import commande.SaisieErroneeException;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

// "Object Oriented Software Engineering" and is issued under the open-source
// license found at www.lloseng.com 
/**
 * This class overrides some of the methods in the abstract superclass in order
 * to give more functionality to the server.
 *
 * @author Dr Timothy C. Lethbridge
 * @author Dr Robert Lagani&egrave;re
 * @author Fran&ccedil;ois B&eacute;langer
 * @author Paul Holden
 * @version July 2000
 */
public class EchoServer extends AbstractServer {

    public static final String ERRORMSGLOGIN = "ERREUR : Vous tentez de vous connecter une seconde fois";
    //Class variables *************************************************
    /**
     * The default port to listen on.
     */
    final public static int DEFAULT_PORT = 5555;
    private ChatIF serverUI;
    private ChainAnalyseurServer analyseurSaisieUI = new AnalyseurClose(new AnalyseurGetPort(new AnalyseurQuit(new AnalyseurSetPort(new AnalyseurStart(new AnalyseurStop(null, this),this), this), this), this),this);
    private AbstractAnalyseurClientMessage analyseurMsgClient;
    //Constructors ****************************************************

    /**
     * Constructs an instance of the echo server.
     *
     * @param port The port number to connect on.
     */
    public EchoServer(int port, ChatIF serverUI) {
        super(port);
        this.serverUI=serverUI;    
         analyseurMsgClient =new AnalyseurLogin(new AnalyseurCreateSondage(null,this),this);
    }

    //Instance methods ************************************************
    /**
     * This method handles any messages received from the client.
     *
     * @param msg The message received from the client.
     * @param client The connection from which the message originated.
     */
    @Override
    public void handleMessageFromClient(Object msg, ConnectionToClient client) {
        String messageTexte = (String) msg;
        try {
            this.analyseurMsgClient.executeCommande(messageTexte, client);
        } catch (Exception ex) {
            String id = client.getInfo("id").toString();
            display("Message received: " + msg + " from " + id);
            String flood = id+">"+msg;
            this.sendToAllClients(flood);
        }
    }

    /**
     * This method overrides the one in the superclass. Called when the server
     * starts listening for connections.
     */
    @Override
    protected void serverStarted() {
        display("Server listening for connections on port " + getPort());
    }

    /**
     * This method overrides the one in the superclass. Called when the server
     * stops listening for connections.
     */
    @Override
    protected void serverStopped() {
        display("Server has stopped listening for connections.");
    }

    //Class methods ***************************************************
    /**
     * This method is responsible for the creation of the server instance (there
     * is no UI in this phase).
     *
     * @param args[0] The port number to listen on. Defaults to 5555 if no
     * argument is entered.
     */
//    public static void main(String[] args) {
//        int port = 0; //Port to listen on
//
//        try {
//            port = Integer.parseInt(args[0]); //Get port from command line
//        } catch (Throwable t) {
//            port = DEFAULT_PORT; //Set port to 5555
//        }
//
//        EchoServer sv = new EchoServer(port,null);
//
//        try {
//            sv.listen(); //Start listening for connections
//        } catch (Exception ex) {
//            System.out.println("ERROR - Could not listen for clients!");
//        }
//    }
//
//    @Override
//    protected void clientConnected(ConnectionToClient client) {
//        display("Quelqu'un s'est connecte : " + client.getInfo("id"));
//    }
//
//    @Override
//    protected synchronized void clientDisconnected(ConnectionToClient client) {
//        display(client.getInfo("id") + " s'est deconnecte");
//    }

    public void display(String message) {
        this.serverUI.display(message);
    }

    
    public void quit() {
        try {
            this.close();
        } catch (IOException ex) {
            Logger.getLogger(EchoServer.class.getName()).log(Level.SEVERE, null, ex);
        }
        System.exit(0);
    }
    
     public void handleMessageFromServerUI(String message) throws IOException {
        try {
            this.analyseurSaisieUI.ChaineAnalyseTexte(message);
        } catch (SaisieErroneeException ex) {
            Logger.getLogger(EchoServer.class.getName()).log(Level.SEVERE, null, ex);
        }
     }
}
//End of EchoServer class
